import { Config } from '../config';
import { clog } from './log';
import { Toast } from 'antd-mobile-rn';
import Storage from './storage';

export const utilsPost = (api, body, state = {}, options) => {
  return new Promise((resolve, reject) => {
    state.LETIME = Date.now();
    state.api = api;
    state.body = parseParaMeter(body);
    // 枚举option中的属性加入到fetch的body中
    if (options) {
      for (let n in options) {
        if (state.body[n]) {
          state.body[n] = Object.assign(state.body[n], options[n]);
        } else {
          state.body[n] = options[n];
        }
      }
    }
    // console.log('httpPOST', state.api, state.body);
    fetch(state.api, state.body)
      .then(response => response.text())
      .then((responseText) => {
        state.LETIME = Date.now() - state.LETIME;
        console.log('httpPOSTRES', state.api, state.LETIME, state.body, responseText);
        let res = JSON.parse(responseText);
        state.res = res;
        resolve(state);
      })
      .catch((error) => {
        state.LETIME = Date.now() - state.LETIME;
        state.ERROR = error;
        console.log('httpPOSTRES', error);
        reject(state);
      });

  });
};

export const utilsGet = (api, body, state = {}, options) => {

  return new Promise((resolve, reject) => {

    if (body) {
      if (api.indexOf('user/') >= 0 || api.indexOf('data/') >= 0) {
        api = `${api}&params=${encodeURI(JSON.stringify(body))}`;
      } else {
        let plist = [];
        Object.keys(body).forEach((o) => {
          plist.push(`${o}=${body[o]}`);
        });
        if (plist.length > 0) {
          api = `${api}?${plist.join('&')}`;
        } else {
          api = `${api}`;
        }
      }
    }

    console.log("utilsGet", api, body, options);

    state.LETIME = Date.now();
    state.api = api;
    fetch(state.api, options)
      .then(response => response.text())
      .then((responseText) => {
        state.LETIME = Date.now() - state.LETIME;
        let res = JSON.parse(responseText);
        state.res = res;
        console.log('httpGETRES:', state.api, state.LETIME, res);
        if(res.code!==0){
          // 如果是用户过期
          if(res.code === -2){
            Storage.clearall()
          }
          Toast.fail(res.msg);
        }
        resolve(state);
      })
      .catch((error) => {
        state.LETIME = Date.now() - state.LETIME;
        state.ERROR = error;
        console.warn('httpGETRES_ERROR:', state);
        reject(state);
      });
  });
};

// 格式化Post参数
export const parseParaMeter = (body) => {
  return {
    method: 'POST',
    headers: {
      'Accept': '*/*',
      'Content-Type': 'application/json',
    },
    'body': JSON.stringify(body),
  };
};

const parseKey = (url, mode, param, isLogin = 0) => {

  let rstring = [];
  rstring.push(mode + '=' + url);
  if (param) {
    Object.keys(param).map((k) => { rstring.push(k + '=' + param[k]) });
    rstring.push('lg' + '=' + isLogin);
    return rstring.join('&').replace(/[_%/]/gim, '&').toLocaleLowerCase();
  }
  return (isLogin).replace(/[_%]/gim, '').toLocaleLowerCase();
};

export const Http = {

  TIME: [],
  TIMECOUNT: 0,

  success(resolve, reject, resData, timeIndex) {

    clearTimeout(this.TIME[timeIndex]);
    let { res } = resData;
    resolve(res);

  },

  error(reject, err, timeIndex) {

    clearTimeout(this.TIME[timeIndex]);
    // clog.info ('httpError', '接口请求错误', err);
    Toast.fail('接口请求错误');
    reject(err);

  },

  // 超时提示
  complete(timeIndex, parseValue) {
    return new Promise((resolve, reject) => {

      this.TIME[timeIndex] = setTimeout(() => {

        reject('API请求超时');
        // clog.info ('httpError','API请求超时', parseValue);
        Toast.fail('API请求超时');

      }, 12000);

    });
  },
  // 登录用户附加UserName  Token 参数
  parseAuth(body = {}) {

    // let Auth = Storage.getSession();
    // if (Auth) {
    //   return { ...body, UserIDGuid: Auth.UserIDGuid };
    // } else {
    //   return body;
    // }
    return body;
  },

  Post(api, body, options) {

    return new Promise((resolve, reject) => {
      let timeIndex = this.TIMECOUNT++;
      Promise
        .race([
          utilsPost(Config.APIRoot + api, this.parseAuth(body), {}, options),
          this.complete(
            timeIndex, { url: Config.APIRoot + api, parse: this.parseAuth(body) })
        ])
        .then((res) => this.success(resolve, reject, res, timeIndex))
        .catch((err) => this.error(reject, err, timeIndex));

    });

  },

  Get(api, body, options) {

    return new Promise((resolve, reject) => {
      let timeIndex = this.TIMECOUNT++;
      let urlList = [];

      // if (api.indexOf("params") >= 0) {
      //     urlList.push(utilsGet(Config.APIRoot + api, {}));
      //     urlList.push(this.complete(
      //         timeIndex, { url: Config.APIRoot + api, parse: this.parseAuth(body) }));
      // } else {
      //     urlList.push(utilsGet(Config.APIRoot + api, this.parseAuth(body)));
      // urlList.push(this.complete(
      //     timeIndex, { url: Config.APIRoot + api, parse: this.parseAuth(body) }));
      // }

      Promise
        .race([utilsGet(Config.APIRoot + api, this.parseAuth(body), {}, options),
          this.complete(
            timeIndex, { url: Config.APIRoot + api, parse: this.parseAuth(body) })])
        .then((res) => this.success(resolve, reject, res, timeIndex))
        .catch((err) => this.error(reject, err, timeIndex));

    });

  },

  GetBack(api, body) {

    return new Promise((resolve, reject) => {
      let timeIndex = this.TIMECOUNT++;
      let urlList = [];

      if (api.indexOf('params') >= 0) {
        urlList.push(utilsGet(Config.APIRoot + api, this.parseAuth(body)));
        urlList.push(utilsGet(Config.APIRoot + api, this.parseAuth(body)));
      }


      Promise
        .race([
          utilsGet(Config.APIRoot + api, this.parseAuth(body)),
          this.complete(
            timeIndex, { url: Config.APIRoot + api, parse: this.parseAuth(body) })
        ])
        .then((res) => this.success(resolve, reject, res, timeIndex))
        .catch((err) => this.error(reject, err, timeIndex));
    });

  },

  // 拼接存储规则
  parseRule(url, mode = 'Get', params = {}, isLogin = 0) {

    let Auth = cacheSession.getSession();
    if (Auth) {
      isLogin = 1;
    }
    mode = mode.toLocaleLowerCase();
    return parseKey(url, mode, params, isLogin);

  },

};
